<template>
    <div class="app-container">
        <levelbar></levelbar>
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="query" ref="query" :rules="rules" slot="form" label-width="80px" label-position="right">
                <!-- edit by cuihd at 2018/8/8 -->
                <!-- 将原“查询条件”的所属省、市区、区县删掉，这些查询条件区分度小，可能会查出几十万的数据 -->
                <!-- 直接使用区分度高的学校名称来查询，学校名称为必填项 -->
                <!-- <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="省份" prop="province">
                            <province v-model="query.province" @change="provinceChange"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市区" prop="city">
                            <city v-model="query.city" :province="query.province" @change="cityChange"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县" prop="county">
                            <region v-model="query.county" :city="query.city" @change="countyChange"></region>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称" prop="schoolName">
                            <el-autocomplete v-model="query.schoolName" :fetch-suggestions="remoteMethod" placeholder="请输入关键词" @select="queryAllGrade" style="width:100%"></el-autocomplete>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="this.schoolType == '0'">
                        <el-form-item label="年级" prop="grade">
                            <el-select v-model="query.grade" clearable placeholder="请选择" style="width:100%;" @change="queryAllClass( query.grade )">
                                <el-option v-for="item in gradeList" :key="item.pId" :label="item.sName" :value="item.pId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级名称" prop="classId">
                            <el-select v-model="query.classId" clearable placeholder="请选择" style="width:100%;">
                                <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="this.schoolType == '1'">
                        <el-form-item label="e学云ID号" prop="eID">
                            <el-input v-model="query.eID" placeholder="请输入e学云ID号" style="width:100%" :maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8" v-if="this.schoolType == '0'"> 
                        <el-form-item label="e学云ID号" prop="eID">
                            <el-input v-model="query.eID" placeholder="请输入e学云ID号" style="width:100%" :maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学生姓名" prop="studentName">
                            <el-input v-model="query.studentName" placeholder="请输入学生姓名" style="width:100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="家长姓名" prop="parentName">
                            <el-input v-model="query.parentName" placeholder="请输入" style="width:100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="this.schoolType == '1'">
                        <el-form-item label="家长手机" prop="parentPhone">
                            <el-input v-model="query.parentPhone" placeholder="请输入" style="width:100%" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <!-- <el-row :gutter="41">
                    <el-col :span="8"  v-if="this.schoolType == '0'">
                        <el-form-item label="家长手机" prop="parentPhone">
                            <el-input v-model="query.parentPhone" placeholder="请输入" style="width:100%" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="家长e学云ID" prop="parentEId">
                            <el-input v-model="query.parentEId" placeholder="请输入" style="width:100%" :maxlength="9"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <div class="top-line">
                    <el-button type="primary" class="top-btn" @click="onSubmit('query')">查询</el-button>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button @click="addStudent()">新增</el-button>
                    <el-button @click="batchDeleteStudent()" :loading="btnLoading">批量删除</el-button>
                </div>
            </div>
            <el-table :data="tableData" border v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection" width="55"></el-table-column>
    
                <!-- <el-table-column align="center" label="学籍号">
                    <template scope="scope">
                        <span>{{scope.row.schoolrollCode | isNull}}</span>
                    </template>
                </el-table-column> -->
    
                <el-table-column align="center" label="e学云ID号">
                    <template scope="scope">
                        <span>{{scope.row.exueCode  | isNull}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column align="center" label="姓名">
                    <template scope="scope">
                        <span>{{scope.row.studentName | isNull}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column align="center" label="性别">
                    <template scope="scope">
                        <span>{{scope.row.studentSex | isNull}}</span>
                    </template>
                </el-table-column>
    
                <!-- <el-table-column align="center" label="关联家长数">
                    <template scope="scope">
                        <span>{{!scope.row.relevanceParentNum?'0':scope.row.relevanceParentNum}}</span>
                    </template>
                </el-table-column> -->
    
                <el-table-column align="center" label="创建时间" width="170">
                    <template scope="scope">
                        <span>{{ scope.row.createTime | parseTime}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column align="center" label="最后登陆时间" width="170">
                    <template scope="scope">
                        <span>{{ scope.row.lastLoginTime | parseTime }}</span>
                    </template>
                </el-table-column>
    
                <el-table-column align="center" label="初始化密码">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="initPassword(scope.row)">初始化</el-button>
                    </template>
                </el-table-column>
    
                <el-table-column label="操作" width="240px">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="classInfor(scope.row)">班级信息</el-button>
                        <el-button type="text" class="btn-success" @click="studentInfor(scope.row)">学生信息</el-button>
                        <el-button type="text" class="btn-success" @click="deleteList(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="pageQuery.total" 
                :current-page.sync="pageQuery.currentpage" 
                :page-sizes="config.pageSizes"
                 :page-size="config.pageSize"
                  @size-change="handleSizeChange"
                   @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <!-- created by cuihd at 20180709 优化批量删除 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>

<script>
    import Levelbar from '../layout/Levelbar';
    import TableLayout from 'components/TableLayout';
    import province from 'components/CascadeRegion/province';
    import city from 'components/CascadeRegion/city';
    import region from 'components/CascadeRegion/region';
    import { querySchoolByName } from 'api/common';
    import { getStudentList, initializePassword, deleteBatchStudentInfo, deleteBatchStudentInfoProgress, getGrade, getClass } from 'api/studentMange';
    import { mapGetters, mapState, mapActions } from 'vuex';
    import validate from '@/utils/validate';

    export default {
        name: 'studentManage',
        components: { Levelbar, TableLayout, province, city, region},
        data() {
            return { 
                schoolLoading: false,
                loading: false, 
                btnLoading:false, 
                schoolType: '0',
                options: [],
                schoolList: [],
                gradeList: [],
                classList: [],
                tableData: [],
                pageQuery: {
                    currentpage: 1,
                    total: 0
                },
                query: {
                    province: '',
                    city: '',
                    county: '',
                    classState: '0',
                    schoolId: '',
                    schoolName: '',
                    eID: '',
                    grade: '',
                    classId: '',
                    className: '',
                    studentName: '',
                    parentName: '',
                    parentPhone: '',
                    parentEId: ''
                },
                multipleSelection: [],
                rules: {
                    // province: [ // edit by cuihd at 2018/8/8
                    //     { required: true, message: '请输入省份' }
                    // ],
                    schoolName:[ // edit by cuihd at 2018/8/8
                        {required: true, message: '请先输入学校'}
                    ],
                    eID: [...validate.exueCode()],
                    parentEId: [...validate.exueCode()],
                    parentPhone: [...validate.phone()]
                },
                /**
                 * created by cuihd at 20180709
                 * 优化批量删除学生
                 * 添加相关变量
                 */
                dialogTitle: '正在批量删除学生...',
                dialogTimeout: false,
                progress: 0
            }
        },
        created() {
            // this.queryData();
        },
        watch: {// 局部刷新列表
            cacheUpdated(val) {
                val==2 && this.queryData();
            }
        },
        computed: {
            ...mapGetters([
                'uid'
            ]),
            ...mapState({
                config: state => state.config.table,
                cacheUpdated: state => state.app.cacheUpdated // 局部刷新列表
            })
        },
        methods: {
            ...mapActions(['ChangePageSize']),
            handleSizeChange(val) {
                this.ChangePageSize(val);
                this.$refs.query.validate((valid) => {
                    if (valid) {
                        this.pageQuery.currentpage = 1;
                        this.queryData();
                    }
                })   
            },
            handleCurrentChange(val) {
                this.pageQuery.currentpage = val;
                this.queryData();
            },
            onSubmit(ruleForm) {                
                this.$refs[ruleForm].validate((valid)=>{
                    if(valid){
                        this.pageQuery.currentpage = 1;
                        this.queryData();
                    }
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            queryData() {

                let provinceId = this.query.province;// 省ID
                let cityId = this.query.city; // 市ID
                let areaId = this.query.county; // 区ID
                let schoolId = this.query.schoolId; // 学校名称
                let schoolName = this.query.schoolName; // 学校名称
                let eId = this.query.eID; // exueid
                let grade = this.query.grade; // 年级
                let classId = this.query.classId; // 班级编号
                let studentName = this.query.studentName; // 学生名称
                let parentName = this.query.parentName; // 家长名称
                let parentPhone = this.query.parentPhone; // 家长电话
                let parentExueCode = this.query.parentEId; // 家长exuecode
                this.loading = true;
                getStudentList(
                    this.pageQuery.currentpage,
                    this.config.pageSize,
                    provinceId, // 省ID
                    cityId, // 市ID
                    areaId, // 区ID
                    schoolId,
                    schoolName, // 学校名称
                    eId, // exueid
                    grade, // 年级
                    classId,
                    studentName, // 学生名称
                    parentName, // 家长名称
                    parentPhone, // 家长电话
                    parentExueCode, // 家长exuecode
                ).then(response => {
                    this.tableData = [];
                    if (response.data.content) {
                        this.tableData = response.data.content.list;
                        this.pageQuery.total = response.data.content.pagination.total;
                    }
                    this.loading = false;                    
                }).catch(() => {
                    this.loading = false;
                });
            },

           // 新增
            addStudent() {
                this.$router.push({ path: 'addStudentPage' });
            },

            // 学生信息
            studentInfor(obj) {
                this.$router.push({ path: `studentInforPage/${obj.studentId}`});
            },

            // 班级信息
            classInfor(obj) {
                this.$router.push({ path: `classInforPage/${obj.studentId}`});
            },

            // 初始化密码
            initPassword(obj) {
                this.$confirm('确定初始化用户【'+obj.studentName+'】的密码？', ' ', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ' // warning
                }).then(() => {
                    initializePassword(obj.studentId).then(response => {
                        if (response.data.status == 200) {
                            this.$message.success('初始化密码成功，新密码是111111');
                            this.queryData();
                        } else {
                            this.$message.error(response.data.errorMsg);
                        }
                    })
                }).catch(() => {      
                    this.$message.info('已取消');   
                });
            },

            // 删除功能
            deleteStudent(studentId, status) {
                let txt = status == '0'?'确定删除该学生？':'此操作将批量删除选中学生, 是否继续?';
                this.$confirm(txt, '', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ', // warning
                    title: '  '
                }).then(() => {
                    if (status == '1') this.btnLoading = true;                  
                    this.loading = true;
                    deleteBatchStudentInfo(studentId).then(response => {
                        this.$message.success(response.data.errorMsg);
                        this.queryData();
                        this.btnLoading = false;
                    }).catch(() => {
                        this.loading = false;
                        this.btnLoading = false;
                    })
                }).catch((e) => {
                    this.$message.info('已取消删除');     
                });            
            },
         
            // 批量删除
            batchDeleteStudent() {               
                let studentIdList = [];
                if (this.multipleSelection.length == 0) {
                    this.$message('请选择需要删除的学生');
                    return;
                }
                for (let index=0; index<this.multipleSelection.length;index++) {
                    studentIdList.push(this.multipleSelection[index].studentId);
                }
                let studentId = studentIdList.join(',');
                this.$confirm('此操作将批量删除选中学生, 是否继续?', '', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ', // warning
                    title: '  '
                }).then(() => {
                    this.btnLoading = true;                  
                    this.loading = true;
                    deleteBatchStudentInfo(studentId).then(res => {
                        // this.$message.success(response.data.errorMsg);
                        // this.queryData();
                        // this.btnLoading = false;
                        /**
                         * created by cuihd at 20180710
                         * 优化批量删除教师
                         * 添加相关变量
                         */
                        this.loading = false;
                        let timeStamp = res.data.content.timeStamp;
                        let totalNum = res.data.content.totalNum;
                        this.dialogTitle = '正在批量删除学生...';
                        this.dialogTimeout = true;
                        this.progress = 0;
                        this.batchProgress(timeStamp, totalNum);
                    }).catch(() => {
                        this.loading = false;
                        this.btnLoading = false;
                    })
                }).catch((e) => {
                    this.$message.info('已取消删除');     
                });
            },

            // created by cuihd at 20180710
            // 轮询接口获取未处理的数量
            batchProgress(timeStamp, totalNum) { // 递归轮询deleteBatchStudentInfoProgress接口
                totalNum = Number(totalNum); // 强转成number类型
                deleteBatchStudentInfoProgress(timeStamp).then(res => {
                    if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                        if (res.data.content != 0) {
                            this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                            setTimeout(() => {
                                this.batchProgress(timeStamp, totalNum);
                            }, 1000);
                        } else {
                            this.btnLoading = false;
                            this.dialogTitle = '批量删除学生成功';
                            this.progress = 100;
                            setTimeout(() => {                       
                                this.dialogTimeout = false;
                                this.queryData();
                            }, 500)
                        }
                    }else{
                        this.dialogTimeout = false;
                        this.$message({
                            message: '批量删除失败！',
                            type: 'error'
                        });
                        this.queryData();
                    }
                    
                }).catch(err => {
                    console.log(err);
                })
            },

             // 删除
            deleteList(obj) {
                this.$confirm('确定删除该学生？', '', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ', // warning
                    title: '  '
                }).then(() => {         
                    this.loading = true;
                    deleteBatchStudentInfo(obj.studentId).then(response => {
                        this.$message.success(response.data.errorMsg);
                        this.queryData();
                    }).catch(() => {
                        this.loading = false;
                    })
                }).catch((e) => {
                    this.$message.info('已取消删除');     
                });
            },

            // 模糊查询学校名称
            remoteMethod(query, cb) {
                query = query.trim();
                if(query==''){
                    cb([{value:'无数据'}]);
                    this.$nextTick(()=>{
                        let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                        firstSelect.addClass('remoteMethodScy');
                    })
                }
                if (this.query.schoolName!=query && this.query.schoolName!='') {
                    this.queryAllGrade('');
                }
               
                if (query) {
                    querySchoolByName(query,this.query.province,this.query.city,this.query.county).then(response => {
                        this.schoolList = response.data.content;
                        if (this.schoolList==''){
                            return;
                        }
                    }).then(() => {
                        let results = this.schoolList.filter(this.createStateFilter(query));
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(() => {
                            if(results.length){
                                let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                                firstSelect.removeClass('remoteMethodScy');
                                cb(results)
                            }else{
                                cb([{value:'无数据'}]);
                                this.$nextTick(()=>{
                                    let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                                    firstSelect.addClass('remoteMethodScy')
                                })
                            }
                        }, 200 * Math.random());
                    });
                } else {
                    this.query.schoolId = '';
                    this.schoolType = '0';
                    this.query.grade = '';
                    this.gradeList = [];
                    this.query.classId = '';
                    this.classList = [];
                    cb([{value:'无数据'}]);
                    this.$nextTick(()=>{
                        let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                        firstSelect.addClass('remoteMethodScy')
                    })
                }  
            },
            createStateFilter(query) {
                return (state) => {
                    state.value = state.schoolName; 
                    return (state.value.toLowerCase().includes(query.toLowerCase()));
                };
            },
            provinceChange() {
                this.query.schoolId = '';
                this.query.schoolName = '';
            },
            cityChange() {
                this.query.schoolId = '';
                this.query.schoolName = '';
            },
            countyChange() {
                this.query.schoolId = '';
                this.query.schoolName = '';
            },
            // remoteMethod(query) {
            //     if (query !== '') {
            //         this.schoolLoading = true;
            //         setTimeout(() => {
            //             this.schoolLoading = false;
            //             querySchoolByName(query).then(response => {
            //                 this.schoolList = response.data.content;
            //             });
            //         }, 200);
            //     } else {
            //         this.query.schoolId='';
            //     }
            // },

            // 年级列表
            queryAllGrade(val) {
                this.query.grade = '';
                this.gradeList = [];
                this.schoolType = val.schoolType;

                if(val.schoolId) {
                    this.query.schoolId = val.schoolId;
                
                    if (this.schoolType == '1') {
                        let schoolId = this.query.schoolId;
                        getClass(null, schoolId).then(response => {
                            this.classList = response.data.content;
                        });
                    } else {
                        getGrade(val.schoolId).then(response => {
                            this.gradeList = response.data.content;
                        })
                    }  
                } else {
                    this.query.schoolName = '';
                    this.schoolType = '0';
                }
                
            },

            // 班级列表
            queryAllClass(gradeId) {
                this.query.classId = '';
                this.classList = [];
                
                if(this.query.grade) {
                    let schoolId = this.query.schoolId;
                    getClass(gradeId, schoolId).then(response => {
                        this.classList = response.data.content;
                    })
                }
               
            }
        }

    }
</script>

<style lang="scss" scoped>
.app-container {
    position: relative;
    padding: 20px 20px 10px;
    $bgcolor: #fff;
    .app-levelbar {
        height: 35px;
    }
}
</style>

